<template>
  <a-modal
    v-model.trim="showModal"
    :title="title"
    @cancel="onCancel"
  >
    <a-form-model
      :model="organizationForm"
      ref="organizationForm"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="rules"
    >
      <a-form-model-item label="组织名称" prop="name">
        <a-input
          v-model.trim="organizationForm.name"
          :maxLength="20"
          placeholder="请输入组织名称"
        />
      </a-form-model-item>
      <a-form-model-item label="是否小租户" prop="smallTenancyStatus">
        <a-radio-group v-model="organizationForm.smallTenancyStatus" :disabled="organizationForm.organizationId === organizationForm.id">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="2">否</a-radio>
        </a-radio-group>
      </a-form-model-item>
    </a-form-model>
    <template #footer>
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" @click="onSave">确定</a-button>
    </template>
  </a-modal>
</template>
<script>
import cloneDeep from "lodash.clonedeep";
import { addDepartment, updateDepartment } from "@/services/userManage.js";
import Regex from "@/utils/regex.js";
import { storeQiankun } from 'if-qiankun-config'

const qianKunInstance = storeQiankun.Instance
const originForm = {
  code: "",
  id: "",
  name: "",
  parentCode: "",
  parentId: "",
  status: "",
  smallTenancyStatus: 2 // 是否是小租户
};

export default {
  name: "organizationForm",
  data() {
    const nameCheckFun = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("名称不能为空"));
      } else if (!Regex.userName.test(value)) {
        callback(new Error("请输入汉字、字母、数字"));
      } else {
        callback();
      }
    };
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
      title: "组织",
      showModal: false,
      organizationForm: { ...originForm },
      type: "add",
      rules: {
        name: [{ required: true, validator: nameCheckFun, trigger: "blur" }],
        smallTenancyStatus: [{ required: true, trigger: "change" }]
      },
      editOriginData: null // 编辑时原始的数据
    };
  },
  mounted() {},
  methods: {
    async show(data, type) {
      this.type = type;
      if (type === "edit") {
        this.organizationForm = { ...data };
        this.editOriginData = { ...data };
        this.title = "编辑部门";
      } else {
        this.organizationForm = { ...originForm, parentId: data.id };
        this.title = "新增部门";
      }
      this.showModal = true;
      this.$refs.organizationForm?.clearValidate();
    },
    onCancel() {
      this.showModal = false;
      this.organizationForm = { ...originForm };
    },
    async onSave() {
      // 1. 必要的检查
      if (!this.checkValid()) return;
      // 2. 匹配接口处理参数
      let apiName = this.type === "edit" ? updateDepartment : addDepartment;
      let params = { ...this.organizationForm };
      // 3. 是否需要弹窗判断
      const needPopGroupConfWindow = this.isPopWindow(params);
      const postData = cloneDeep(params);
      const isUpdateNecessary = this.isUpdateNecessary(params);
      // 4. 需要弹窗的特别处理
      if (needPopGroupConfWindow) {
        postData.smallTenancyStatus = 2; // 需要弹窗时, 参数重置成非小租户，后续弹窗后选择了再补
        // 编辑时, 如果只有小租户变更，则不去调用接口，不去提示，直接弹窗
        if (this.type === "edit" && !isUpdateNecessary) {
          this.$emit("success", { id: postData.id, needPopGroupConfWindow, noRefresh: true}); // 通知外部
          this.showModal = false;
          this.selfDepartmentUpdate(params, postData) // 通知外部更新导航栏
          return
        }
      }
      // 5. 接口调用
      const { data: { message, code, data } } = await apiName(postData);
      this.showModal = false;
      if (code !== 200) {
        this.$message.error(message || "保存失败");
        return;
      }
      const noMessage = this.type === 'edit' && needPopGroupConfWindow;
      !noMessage && this.$message.success("保存成功"); // 应测试要求, 编辑时, 变更为小租户, 不提示
      this.$emit("success", { id: data?.id ? data.id : postData.id, needPopGroupConfWindow});
      // 6. 编辑状态的处理逻辑
      if (this.type === 'edit') {
        this.selfDepartmentUpdate(params, postData) // 通知外部更新导航栏
        // 其他可能的逻辑 TODO
      }
    },
    // 自己部门的更新逻辑
    selfDepartmentUpdate(params, postData) {
      // 匹配当前编辑的部门是否是自己的部门
      if (qianKunInstance.state.value.departmentId !== postData.id) {
        return
      }
      // 设置当前状态
      const userName = params.smallTenancyStatus === 1 ? postData.name : qianKunInstance.state.value.enterpriseList[0].name
      Object.assign(qianKunInstance.state.value, {
        userName
      })
      qianKunInstance.actions.setGlobalState(qianKunInstance.state)
    },
    // 通信时选择的是 小租户，分组配置是否弹窗的处理器
    // 原始数据从2变成1的时需要 弹窗
    // 新增直接选择小租户需要 弹窗
    isPopWindow(params) {
      // 新增时
      if (this.type === 'add') {
        return params.smallTenancyStatus === 1;
      }
      // 编辑时
      if (!this.editOriginData) return false;
      return this.editOriginData.smallTenancyStatus === 2 && params.smallTenancyStatus === 1;
    },
    // 是否需要变更, 移除小租户的影响, 新旧参数对比
    isUpdateNecessary(params) {
      if (this.type === 'add') return false;
      const originData = cloneDeep(this.editOriginData);
      const paramsData = cloneDeep(params);
      delete originData.smallTenancyStatus;
      delete paramsData.smallTenancyStatus;
      return JSON.stringify(originData) !== JSON.stringify(paramsData);
    },
    checkValid() {
      let bol = false;
      this.$refs.organizationForm.validate((valid) => {
        bol = Boolean(valid);
      });
      return bol;
    }
  }
};
</script>
<style lang="less" scoped></style>
